package webmarket.test.selenium.common;

import java.util.List;

import junit.framework.TestCase;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public abstract class SeleniumTestCase extends TestCase {
	protected SeleniumTestHelper helper;

	protected void testDateFormat(String id) {
		// Arrange
		helper.getById(id).sendKeys("05/08/2013");

		// Act
		helper.getById("searchForm").submit();

		// Assert
		assertTrue(helper.isElementPresentById("userinfo"));
		assertTrue(helper.getById("userinfo").getText().toLowerCase()
				.contains("hibás formátum"));
	}

	protected void testIpFormat(String id) {
		// Arrange
		helper.getById(id).sendKeys("12345667899");

		// Act
		helper.getById("searchForm").submit();

		// Assert
		assertTrue(helper.isElementPresentById("userinfo"));
		assertTrue(helper.getById("userinfo").getText().toLowerCase()
				.contains("hibás formátum"));
	}

	protected void testModalShow(String modalId, String showButtonClass,
			String showButtonTag, String showButtonText)
			throws NullPointerException {
		// Arrange
		WebElement modal = helper.getById(modalId);
		WebElement paramShowButton = getModalShowButton(showButtonClass,
				showButtonTag, showButtonText);

		// Act
		paramShowButton.click();

		// Assert
		assertEquals(modal.getCssValue("display"), "block");
	}

	protected WebElement getModalShowButton(String showButtonClass,
			String showButtonTag, String showButtonText) {
		List<WebElement> buttons = helper.getDriver().findElements(
				By.className(showButtonClass));
		WebElement paramShowButton = null;
		for (WebElement button : buttons) {
			if (button.getTagName().equals(showButtonTag)
					&& button.getText().equals(showButtonText)) {
				paramShowButton = button;
				break;
			}
		}
		if (paramShowButton == null) {
			throw new NullPointerException(
					"Modal show button not found on page!");
		}
		return paramShowButton;
	}

	protected WebElement getPageLink() {
		List<WebElement> links = helper.getDriver().findElements(
				By.tagName("a"));
		WebElement pageLink = null;
		for (WebElement link : links) {
			if (link.getAttribute("onclick").equals("setpage(2)")) {
				pageLink = link;
				break;
			}
		}
		if (pageLink == null) {
			throw new NullPointerException(
					"No paging link found, please provide more test data to test this function.");
		}
		return pageLink;
	}
}
